﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using AMS.DD35.WebMVC3.Models;
using AMS.Core.Services;
using AMS.DD35.WcfConnector;
using AMS.Core.Data;
using AMS.Core.Cryptography;

namespace AMS.DD35.WebMVC3.Controllers
{
    public class RegisterController : Controller
    {
        IRegisterService _register = new RegisterProxy();

        //
        // GET: /Register/Register

        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Register/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                IHasher hasher = new Hasher();
                string pwHash = hasher.GetHash(model.Password);
                LoginData lData = new LoginData(model.UserName, pwHash);
                RegistrationData rData = new RegistrationData(lData, model.FirstName, model.LastName, model.Email);

                try
                {
                    _register.AttemptRegister(rData);
                    TempData[State.Constants.Success] = State.Constants.Success;
                    //return RedirectToAction("Login", "Login");
                    return View();
                }
                catch
                {
                    TempData[State.Constants.Success] = null;
                    ModelState.AddModelError("", "Username may already be in use.");
                    return View(model);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
    }
}
